global.cdn = "http://wuliaoqing.gitee.io/ship";
global.config = "dist";
const os = require('os');
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const Basics = require('./webpack.config.basic.js');
const parallel = os.cpus().length - 1;

module.exports = merge(Basics, {
    // 生成 source map
    devtool: "cheap-module-source-map",

    // 优化
    optimization: {
        // 在编译时出现错误时，使用跳过发射阶段
        noEmitOnErrors: true,
        // 压缩 js 文件
        minimizer: [
            // 压缩 js
            new TerserPlugin({
                terserOptions: {
                    compress: {
                        drop_console: true
                    },
                    output: {
                        comments: false,
                        safari10: true
                    },
                    mangle: true
                },
                sourceMap: true,
                cache: true,
                parallel: parallel
            }),

            // 压缩css
            new OptimizeCSSAssetsPlugin({
                assetNameRegExp: /\.css\.*(?!.*map)/g,
                cssProcessor: require("cssnano"),
                cssProcessorOptions: {
                    discardComments: {
                        removeAll: true
                    },
                    safe: true,
                    autoprefixer: false
                },
                canPrint: true
            })
        ]
    },

    // 配置 正式环境的接口
    resolve: {
        alias: {
            'port': path.join(__dirname, '.', 'common', 'port'),
        }
    },

    // 插件
    plugins: [
        // 设置图片资源cdn
        new webpack.DefinePlugin({
            assets_cdn:JSON.stringify("http://q82c48j8i.bkt.clouddn.com/")
        }),
        // new BundleAnalyzerPlugin(),

        // 清除无用chunk
        new CleanWebpackPlugin(
            [global.dist + "/js/*.chunk.*", global.dist + "/css/*.chunk.*"],
            {
                root: "",
                verbose: true,
                dry: false
            }
        ),

        // 生成版本号
        new AssetsPlugin({
            filename: 'map.json',
            path: global.dist,
            prettyPrint: true,
            fullPath: false,
            processOutput: function(assets) {
                return JSON.stringify({
                    "v": global.now
                });
            }
        })
    ],

    // 统计信息
    stats: {
        // 添加构建模块信息
        modules: false
    }
});
